﻿using System.Text;
using RpcCacheClient.Interface;
using RpcHelper;
using RpcSync.DAL;
using RpcSync.Model;

namespace RpcSync.Collect.Collect
{
    internal class RemoteServerCollect : IRemoteServerCollect
    {
        private IRemoteServerConfigDAL _BasicDAL;
        private ILocalCacheController _Cache;

        public RemoteServerCollect(IRemoteServerConfigDAL basicDAL, ILocalCacheController cache)
        {
            this._BasicDAL = basicDAL;
            this._Cache = cache;
        }
        public long[] GetAllServer(int regionId)
        {
            RemoteServer[] server = this._GetAllServer();
            if (regionId == 0)
            {
                return server.ConvertAll(a => a.Id);
            }
            else
            {
                return server.Convert(a => a.RegionId == regionId, a => a.Id);
            }
        }
        public long[] GetServerId(int regionId, List<long> sysTypeId)
        {
            RemoteServer[] server = _GetAllServer();
            if (regionId == 0)
            {
                return server.Convert(a => sysTypeId.IsExists( a.SystemType), a => a.Id);
            }
            else
            {
                return server.Convert(a => a.RegionId == regionId && sysTypeId.IsExists(a.SystemType), a => a.Id);
            }
        }
        private RemoteServer[] _GetAllServer()
        {
            string key = "AllServer";
            if (this._Cache.TryGet(key, out RemoteServer[] servers))
            {
                return servers;
            }
            servers = this._BasicDAL.GetServer();
            this._Cache.Set(key, servers, new TimeSpan(0, 0, Tools.GetRandom(60, 180)));
            return servers;
        }
    }
}
